package com.ych.modules.common.service.impl;

import com.google.code.kaptcha.Producer;
import com.ych.modules.common.entity.ViewCaptchaEntity;
import com.ych.modules.common.service.ICaptchaService;
import com.ych.redis.RedisUtil;
import com.ych.redis.config.RedisKeyConfig;
import com.ych.utils.DateUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Author: Usopp.tsui
 * Date: 2020/12/19
 * Time: 16:18
 * Description:
 */
@Service("ICaptchaService")
public class CaptchaServiceImpl implements ICaptchaService {
    @Autowired
    private Producer  producer;
    @Autowired
    private RedisUtil redisUtil;//redis查询

    @Override
    public void getCaptcha(HttpServletResponse response, String uuid) {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        if (StringUtils.isBlank(uuid)) {
            throw new RuntimeException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();
        ViewCaptchaEntity viewCaptchaEntity = new ViewCaptchaEntity();
        viewCaptchaEntity.setUuid(uuid);
        viewCaptchaEntity.setCode(code);
        //1分钟后过期
        viewCaptchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 1));
        String key = RedisKeyConfig.captchaKey + uuid;
        redisUtil.redisTemplate().opsForValue().set(key, viewCaptchaEntity);
        redisUtil.redisTemplate().expire(key, 60, TimeUnit.SECONDS);
        ServletOutputStream out = null;
        BufferedImage image = null;
        try {
            out = response.getOutputStream();
            image = producer.createImage(code);
            ImageIO.write(image, "jpg", out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            image.flush();//清空缓冲区
            IOUtils.closeQuietly(out);// 关流
        }
    }


    @Override
    public void validate(String uuid, String code) {
        String key = RedisKeyConfig.captchaKey + uuid;
        ViewCaptchaEntity viewCaptchaEntity = (ViewCaptchaEntity) redisUtil.redisTemplate().opsForValue().get(key);
        if (viewCaptchaEntity == null) {
            throw new RuntimeException("验证码已过期,请刷新验证码后重新输入");
        }
        redisUtil.redisTemplate().delete(key);
        if (!(viewCaptchaEntity.getCode().equalsIgnoreCase(code)
                && viewCaptchaEntity.getExpireTime().getTime() >= System.currentTimeMillis())) {
            throw new RuntimeException("验证码不正确,请刷新验证码后重新输入");
        }
    }
}
